package com.ganzi.ganziserver.service.imp;


import com.ganzi.ganziserver.dao.FanCollectDao;
import com.ganzi.ganziserver.dao.SchoolInformationDao;
import com.ganzi.ganziserver.rabbit.send.SendQueryThread;
import com.ganzi.ganziserver.service.QueryThreadService;
import com.ganzi.ganziserver.service.SendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *查询盘管状态数据的线程
 *  目前采用的是一个采集器一个线程（如果后期采集器太多 可以采用一个学校一个线程，每次查询学校所有状态数据）
 * */
@Service
public class QueryThreadServiceImp implements QueryThreadService{
    private static Logger log = LoggerFactory.getLogger(QueryThreadServiceImp.class);

    @Autowired
    SendService sendService;
    @Autowired
    FanCollectDao collectDao;
    @Autowired
    SchoolInformationDao schoolDao;

    @Value("${queryFan.queryGapTime}")
    private int queryGapTime;

    public static Map<String,Thread> collectionQueue = new HashMap<>();

    @Override
    public void sendQueryOrder(String channelName, long collectId, long schoolId) throws Exception {
        String key = channelName+collectId;
        boolean hasKey = collectionQueue.containsKey(key);
        if(!hasKey){
            Thread thread = new SendQueryThread(sendService,collectDao,schoolDao,schoolId,channelName,collectId,queryGapTime);
            thread.start();
            synchronized(collectionQueue){
                collectionQueue.put(key,thread);
            }
            log.info("创建查询线程："+channelName+collectId+"线程数量："+collectionQueue.size());
        }
    }

    @Override
    public void stopsendQueryOrder(String channelName, long collectId) throws Exception {
        synchronized(collectionQueue){
            String key = channelName+collectId;
            boolean haskey = collectionQueue.containsKey(key);
            if(haskey){
                SendQueryThread thread = (SendQueryThread)collectionQueue.get(key);
                thread.interrupt();
                thread.setCanRun(false);
                collectionQueue.remove(key);
                log.info("删除查询线程："+channelName+collectId+" 剩余线程数："+collectionQueue.size());
            }
        }
    }
}
